<template>
  <div>
    <!-- 搜索城市 -->
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索城市"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <!-- 城市定位 -->
    <div @click="dingwei" class="dingwei">定位</div>
    <!-- 城市列表 -->
    <van-index-bar :index-list="indexList">
      <template v-for="(item, index) in indexList" :key="index">
        <van-index-anchor :index="item" />
        <template v-for="v in cityList">
          <van-cell
            :key="v.城市ID"
            :title="v.行政归属"
            v-if="v.index === item"
            @click="a({ id: v.城市ID, name: v.行政归属 })"
          />
        </template>
      </template>
    </van-index-bar>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { showToast } from 'vant'
import type { Ref } from 'vue'
import { useRouter } from 'vue-router'
import { cityInfoStore } from '../../store/index'
import { cityListQuery, cityDingwei, citySearch } from '../../service/cityService'

const store = cityInfoStore()
const router = useRouter()
const indexList = reactive([
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z'
])
const value = ref('')
const cityInfo = ref({ id: '', name: '' })
const onSearch = async (val: string) => {
  const res = await citySearch({ key: 'S_kv1Ro8FrmQ4UeD9', q: val })
  cityInfo.value = res.data.results[0]
  //将获取到城市数据存储到全局
  // store.cityinfo=cityInfo.value;
  //存储到本地
  localStorage.setItem('city', JSON.stringify(cityInfo.value))
  router.push('/home')
}
const onCancel = () => showToast('取消')
const cityList: Ref<any[]> = ref([])
let location = ref('')
let x = ref('')
let y = ref('')

let citylist = async () => {
  let res = await cityListQuery()
  let list = res.data.msg

  //只取市级
  const regex = /^[\u4e00-\u9fa5\w\W]+市$/
  let shiList = list.filter((item: any) => {
    if (regex.test(item.行政归属)) {
      const spliceLength2 = item.行政归属.lastIndexOf('/')
      let str = item.行政归属.slice(spliceLength2 + 1)
      item.行政归属 = str
      return item
    }
  })
  for (var i = 0; i < shiList.length - 1; i++) {
    shiList[i].index = shiList[i].拼音.slice(0, 1).toUpperCase()
    for (var j = 0; j < shiList.length - i - 1; j++) {
      if (shiList[j].拼音 > shiList[j + 1].拼音) {
        var temp = shiList[j]
        shiList[j] = shiList[j + 1]
        shiList[j + 1] = temp
      }
    }
    if (shiList[j].拼音 === shiList[j - 1].拼音) i++
  }
  cityList.value = shiList
}

//获取到id和城市名称跳转到主页
const a = (val: { id: string; name: string }) => {
  // store.cityinfo=val;
  //存储到本地
  localStorage.setItem('city', JSON.stringify(val))
  router.push('/home')
}

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
}

const dingwei = async () => {
  navigator.geolocation.getCurrentPosition(success, error, options)
  let a1 = `${x.value},${y.value}`
  console.log(22,a1);
  
  let res = await cityDingwei({
    ak: 'sLg7qyrpNjlOTq2usNt1h6TEMcwTGsME',
    output: 'json',
    coordtype: 'wgs84ll',
    location: a1
  })
  location.value = res.data.result?.addressComponent?.city
}

function success(pos: any) {
  var crd = pos.coords
  x.value = crd.latitude
  y.value = crd.longitude
}

function error(err: any) {
  console.log('拒绝', err)
}

onMounted(() => {
  citylist()
})
</script>

<style scoped lang="scss">
.map {
  width: 100%;
  height: 400px;
}
.dingwei {
  padding: 10px;
}
</style>
